<template>
  <div>
    <el-input
      v-model="name"
      :size="size"
      suffix-icon="el-icon-user"
      :placeholder="placeholder || '人员选择'"
      readonly
      :disabled="disabled"
      @click.native="handleSelect"
    />
    <wf-user-select
      ref="user-select"
      :check-type="checkType"
      :default-checked="value"
      @onConfirm="handleUserSelectConfirm"
    />
  </div>
</template>
<script>
import { getUser } from '@/api/system/user'
import WfUserSelect from '@/views/plugin/workflow/process/components/user-select'

export default {
  name: 'UserSelect',
  components: { WfUserSelect },
  props: {
    value: [String, Number],
    // radio单选 checkbox多选
    checkType: { type: String, default: 'radio' },
    size: { type: String, default: 'small' },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    placeholder: String,
    userUrl: { type: String, default: '/api/blade-user/search/user' },
    change: Function
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          const name = []
          const checks = (val + '').split(',')
          const asyncList = checks.map(c => getUser(c))
          Promise.all(asyncList).then(res => {
            res.forEach(r => {
              const data = r.data.data
              if (data) name.push(data.realName)
            })
            this.$set(this, 'name', name.join(','))
          })
        }
      },
      immediate: true
    }
  },
  data: () => ({ name: '' }),
  methods: {
    handleSelect() {
      if (this.readonly || this.disabled) return
      else this.$refs['user-select'].visible = true
    },
    handleUserSelectConfirm(id) {
      this.$emit('input', id)
      this.change && typeof this.change == 'function' && this.change({ value: id })
    }
  }
}
</script>
